package com.hjli.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hjli.common.ShareValues;
import com.hjli.model.ArchiveInfo;
import com.hjli.model.ArticleCommentInfo;
import com.hjli.model.ArticleInfo;
import com.hjli.model.LinkInfo;
import com.hjli.service.impl.ArchiveService;
import com.hjli.service.impl.ArticleService;
import com.hjli.service.impl.CommentService;
import com.hjli.service.impl.LinkService;
import com.hjli.tool.PropertiesTool;
import com.hjli.tool.TemplateTool;

@Controller

public class WebController {
	@Resource
	ArticleService articleService;

	@Resource
	ArchiveService archiveService;

	@Resource
	CommentService commentService;

	@Resource
	LinkService linkService;

	/**
	 * 注释：首页加载，返回值 ModelAndView 时间：2017-06-04 作者：Haojie Li
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/")
	public void index(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map<String, Object> templateMap = new HashMap<String, Object>();

		List<ArticleCommentInfo> commentList = commentService.findCommentInfoByCount(10);

		List<String> commentStrList = new ArrayList<String>();
		for (ArticleCommentInfo comment : commentList) {
			commentStrList.add(comment.getcName() + "：“" + comment.getcContent() + "”");
		}

		List<LinkInfo> linkList = linkService.findByCount(10);

		HttpSession session = request.getSession();
		if (session.getAttribute("shareValue") == null) {
			ShareValues shareValues = new ShareValues();
			Properties webproperty = PropertiesTool.getProperty("web.properties");
			shareValues.setWebname(new String(webproperty.getProperty("webname").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setKeywords(new String(webproperty.getProperty("keywords").getBytes("ISO8859-1"), "UTF-8"));
			shareValues
					.setDescription(new String(webproperty.getProperty("description").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setCopyright(new String(webproperty.getProperty("copyright").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setWebroot(request.getContextPath());
			shareValues.setTitle(shareValues.getWebname());
			shareValues.setArticleList(articleService.pageList(0, 10));
			shareValues.setCommentStrList(commentStrList);
			shareValues.setLinkList(linkList);
			templateMap.put("values", shareValues);
		} else {
			ShareValues shareValues = (ShareValues) session.getAttribute("shareValue");
			Properties webproperty = PropertiesTool.getProperty("web.properties");
			shareValues.setWebname(new String(webproperty.getProperty("webname").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setKeywords(new String(webproperty.getProperty("keywords").getBytes("ISO8859-1"), "UTF-8"));
			shareValues
					.setDescription(new String(webproperty.getProperty("description").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setTitle(shareValues.getWebname());
			templateMap.put("values", shareValues);
		}

		List<ArticleInfo> pageList = new ArrayList<ArticleInfo>();
		Properties props = PropertiesTool.getProperty("page.properties");
		int everyPageNum = Integer.parseInt(props.getProperty("webPageNum").toString());// 每页的数量
		int sumCount = articleService.sumPageNum();
		int sumPageNum;// 总页数
		if (sumCount > 0) {
			if (sumCount % everyPageNum == 0) {
				sumPageNum = sumCount / everyPageNum;
			} else {
				sumPageNum = sumCount / everyPageNum + 1;
			}
		} else {
			sumPageNum = 1;
		}
		pageList = articleService.pageList(0 * everyPageNum, everyPageNum);
		templateMap.put("pageList", pageList);
		templateMap.put("sumPageNum", sumPageNum);
		templateMap.put("linkList", linkList);
		String themeName = "";
		if (session.getAttribute("themeName") == null) {
			Properties property = PropertiesTool.getProperty("theme.properties");
			themeName = property.getProperty("themeName");
			session.setAttribute("themeName", themeName);
		} else {
			themeName = (String) session.getAttribute("themeName");
		}
		TemplateTool.print(templateMap, "page/templates/themes/" + themeName + "", "index.ftl", request, response);
	}

	/**
	 * 归档
	 * 
	 * @author Leo
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("archives")
	public void archives(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> templateMap = new HashMap<String, Object>();

		List<ArchiveInfo> list = archiveService.findAll();
		HttpSession session = request.getSession();
		if (session.getAttribute("shareValue") == null) {
			List<ArticleCommentInfo> commentList = commentService.findCommentInfoByCount(10);
			List<String> commentStrList = new ArrayList<String>();
			for (ArticleCommentInfo comment : commentList) {
				commentStrList.add(comment.getcName() + "：“" + comment.getcContent() + "”");
			}
			List<LinkInfo> linkList = linkService.findByCount(10);
			// 页面共同值
			ShareValues shareValues = new ShareValues();
			Properties webproperty = PropertiesTool.getProperty("web.properties");
			shareValues.setWebname(new String(webproperty.getProperty("webname").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setKeywords(new String(webproperty.getProperty("keywords").getBytes("ISO8859-1"), "UTF-8"));
			shareValues
					.setDescription(new String(webproperty.getProperty("description").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setCopyright(new String(webproperty.getProperty("copyright").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setWebroot(request.getContextPath());
			shareValues.setTitle(shareValues.getWebname());
			shareValues.setArticleList(articleService.pageList(0, 10));
			shareValues.setCommentStrList(commentStrList);
			shareValues.setLinkList(linkList);
			templateMap.put("values", shareValues);
		} else {
			ShareValues shareValues = (ShareValues) session.getAttribute("shareValue");
			Properties webproperty = PropertiesTool.getProperty("web.properties");
			shareValues.setWebname(new String(webproperty.getProperty("webname").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setKeywords(new String(webproperty.getProperty("keywords").getBytes("ISO8859-1"), "UTF-8"));
			shareValues
					.setDescription(new String(webproperty.getProperty("description").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setTitle("归档 | " + shareValues.getWebname());
			templateMap.put("values", shareValues);
		}
		templateMap.put("archiveList", list);

		if (session.getAttribute("themeName") == null) {
			Properties property = PropertiesTool.getProperty("theme.properties");
			session.setAttribute("themeName", property.getProperty("themeName"));
			TemplateTool.print(templateMap, "page/templates/themes/" + property.getProperty("themeName") + "",
					"archives.ftl", request, response);
		} else {
			TemplateTool.print(templateMap, "page/templates/themes/" + (String) session.getAttribute("themeName") + "",
					"archives.ftl", request, response);
		}
	}

	/**
	 * 归档详情
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("archives/detail")
	public @ResponseBody Map<String, Object> archiveDetail(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (request.getParameter("date") == null) {
			resultMap.put("result", "参数有误");
			return resultMap;
		}
		String date = request.getParameter("date");
		List<ArticleInfo> articleList = articleService.findByDate(date);
		resultMap.put("result", articleList);
		return resultMap;
	}

	/**
	 * 友链
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("links")
	public void links(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> templateMap = new HashMap<String, Object>();
		List<LinkInfo> linkList = linkService.findByCount(10);
		HttpSession session = request.getSession();
		if (session.getAttribute("shareValue") == null) {
			List<ArticleCommentInfo> commentList = commentService.findCommentInfoByCount(10);
			List<String> commentStrList = new ArrayList<String>();
			for (ArticleCommentInfo comment : commentList) {
				commentStrList.add(comment.getcName() + "：“" + comment.getcContent() + "”");
			}
			// 页面共同值
			ShareValues shareValues = new ShareValues();
			Properties webproperty = PropertiesTool.getProperty("web.properties");
			shareValues.setWebname(new String(webproperty.getProperty("webname").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setKeywords(new String(webproperty.getProperty("keywords").getBytes("ISO8859-1"), "UTF-8"));
			shareValues
					.setDescription(new String(webproperty.getProperty("description").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setCopyright(new String(webproperty.getProperty("copyright").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setWebroot(request.getContextPath());
			shareValues.setTitle(shareValues.getWebname());
			shareValues.setArticleList(articleService.pageList(0, 10));
			shareValues.setCommentStrList(commentStrList);
			shareValues.setLinkList(linkList);
			templateMap.put("values", shareValues);
		} else {
			ShareValues shareValues = (ShareValues) session.getAttribute("shareValue");
			Properties webproperty = PropertiesTool.getProperty("web.properties");
			shareValues.setWebname(new String(webproperty.getProperty("webname").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setKeywords(new String(webproperty.getProperty("keywords").getBytes("ISO8859-1"), "UTF-8"));
			shareValues
					.setDescription(new String(webproperty.getProperty("description").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setTitle("友链 | " + shareValues.getWebname());
			templateMap.put("values", shareValues);
		}
		templateMap.put("linkList", linkList);
		if (session.getAttribute("themeName") == null) {
			Properties property = PropertiesTool.getProperty("theme.properties");
			session.setAttribute("themeName", property.getProperty("themeName"));
			TemplateTool.print(templateMap, "page/templates/themes/" + property.getProperty("themeName") + "",
					"links.ftl", request, response);
		} else {
			TemplateTool.print(templateMap, "page/templates/themes/" + (String) session.getAttribute("themeName") + "",
					"links.ftl", request, response);
		}

	}

	@RequestMapping("chat")
	public void chat(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> templateMap = new HashMap<String, Object>();
		List<LinkInfo> linkList = linkService.findByCount(10);
		HttpSession session = request.getSession();
		if (session.getAttribute("shareValue") == null) {
			List<ArticleCommentInfo> commentList = commentService.findCommentInfoByCount(10);
			List<String> commentStrList = new ArrayList<String>();
			for (ArticleCommentInfo comment : commentList) {
				commentStrList.add(comment.getcName() + "：“" + comment.getcContent() + "”");
			}
			// 页面共同值
			ShareValues shareValues = new ShareValues();
			Properties webproperty = PropertiesTool.getProperty("web.properties");
			shareValues.setWebname(new String(webproperty.getProperty("webname").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setKeywords(new String(webproperty.getProperty("keywords").getBytes("ISO8859-1"), "UTF-8"));
			shareValues
					.setDescription(new String(webproperty.getProperty("description").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setCopyright(new String(webproperty.getProperty("copyright").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setWebroot(request.getContextPath());
			shareValues.setTitle(shareValues.getWebname());
			shareValues.setArticleList(articleService.pageList(0, 10));
			shareValues.setCommentStrList(commentStrList);
			shareValues.setLinkList(linkList);
			templateMap.put("values", shareValues);
		} else {
			ShareValues shareValues = (ShareValues) session.getAttribute("shareValue");
			Properties webproperty = PropertiesTool.getProperty("web.properties");
			shareValues.setWebname(new String(webproperty.getProperty("webname").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setKeywords(new String(webproperty.getProperty("keywords").getBytes("ISO8859-1"), "UTF-8"));
			shareValues
					.setDescription(new String(webproperty.getProperty("description").getBytes("ISO8859-1"), "UTF-8"));
			shareValues.setTitle("友链 | " + shareValues.getWebname());
			templateMap.put("values", shareValues);
		}
		templateMap.put("linkList", linkList);
//		System.out.println(getWebIP("http://city.ip138.com/ip2city.asp"));
//		String clientNetIp = getWebIP("http://city.ip138.com/ip2city.asp").toString();
//		if(clientNetIp=="ERROR_IP"){
//			response.sendRedirect("404.jsp");
//		}
//		templateMap.put("clientNetIp", clientNetIp);
		if(session.getAttribute("chatUser")==null){
			session.setAttribute("chatUser", new Date().getTime()/1000+"");
			templateMap.put("timestamp",session.getAttribute("chatUser").toString());
		}else{
			templateMap.put("timestamp",session.getAttribute("chatUser").toString());
		}
		
//		System.out.println("timestamp:"+new Date().getTime()/1000+"");
		// HttpSession session = request.getSession();
		if (session.getAttribute("themeName") == null) {
			Properties property = PropertiesTool.getProperty("theme.properties");
			session.setAttribute("themeName", property.getProperty("themeName"));
			TemplateTool.print(templateMap, "page/templates/themes/" + property.getProperty("themeName") + "",
					"chat.ftl", request, response);
		} else {
			TemplateTool.print(templateMap, "page/templates/themes/" + (String) session.getAttribute("themeName") + "",
					"chat.ftl", request, response);
		}
	}

	/*
	 * 获取本地主机IP地址
	 */
	public static String getClientNetIP() {
		// 创建本地主机IP地址对象
		try {
			InetAddress addr = InetAddress.getLocalHost();
			String hostAddr = addr.getHostAddress(); // 获取IP地址
			return hostAddr;
			// String hostName = addr.getHostName(); // 获取本地机器名
			// System.out.println("本地IP地址：" + hostAddr);
			// System.out.println("本地的机器名称：" + hostName);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return "404";
		}
	}

	/**
	 * 获取外网地址
	 * 
	 * @param strUrl
	 * @return
	 */
	public static String getWebIP(String strUrl) {
		try {
			// 连接网页
			URL url = new URL(strUrl);
			BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
			String s = "";
			StringBuffer sb = new StringBuffer("");
			String webContent = "";
			// 读取网页信息
			while ((s = br.readLine()) != null) {
				sb.append(s + "\r\n");
			}
			br.close();
			// 网页信息
			webContent = sb.toString();
			int start = webContent.indexOf("[") + 1;
			int end = webContent.indexOf("]");
			// 获取网页中 当前 的 外网IP
			webContent = webContent.substring(start, end);
			return webContent;

		} catch (Exception e) {
			e.printStackTrace();
			return "ERROR_IP";
		}
	}

	/**
	 * 注释：首页文章分页，每页（自定义）条 ，返回值 Map < String,Object > 时间：2017-06-04 作者：Haojie Li
	 * 
	 * @throws Exception
	 */
	@RequestMapping("pageList")
	public @ResponseBody Map<String, Object> pageList(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<ArticleInfo> pageList = new ArrayList<ArticleInfo>();
		int nowPageNum;// 当前页数
		if (request.getParameter("nowPageNum") == null || request.getParameter("nowPageNum").toString() == "") {
			nowPageNum = 0;
		} else {
			nowPageNum = Integer.parseInt(request.getParameter("nowPageNum").toString());
		}
		PropertiesTool proper = new PropertiesTool();
		Properties property = proper.getProperty("page.properties");
		int everyPageNum = Integer.parseInt(property.getProperty("webPageNum"));// 每页的数量
		int sumCount = articleService.sumPageNum();
		// System.out.println("sumCount:" + sumCount);
		int sumPageNum;// 总页数
		if (sumCount > 0) {
			if (sumCount % everyPageNum == 0) {
				sumPageNum = sumCount / everyPageNum;
			} else {
				sumPageNum = sumCount / everyPageNum + 1;
			}
		} else {
			sumPageNum = 1;
		}

		// 获取到List<ArticleInfo> pageList;
		pageList = articleService.pageList(nowPageNum * everyPageNum, everyPageNum);

		// 传入页面的值
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sumPageNum", sumPageNum);
		map.put("list", pageList);

		resultMap.put("result", map);

		return resultMap;
	}

}
